/**
 * JAVACC DEMO 1.0
 */
package com.apache.excp.core.impl.imp;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apache.excp.ConfigConstant;
import com.apache.excp.RuturnConfig;
import com.apache.excp.core.manager.ImportExecl;
import com.apache.excp.core.manager.plugins.Execlplugins;
import com.apache.excp.core.model.ImportVo;

/**
 * description:  实现将execl导入到数据库
 * @author Hou Dayu 创建时间：2014-7-28  
 */
public class ImportExeclImpl implements ImportExecl {

	private Map<String, Execlplugins> plugins = new HashMap<String, Execlplugins>();

	/**
	 * TODO 实现将execl导入到数据库.  
	 * @see com.zbxsoft.execl.manager.ImportExecl#importData(com.zbxsoft.execl.model.ImportVo)  
	 */
	public Object importData(ImportVo vo) {

		//String key = vo.getKey();

		return getModelList(vo);
	}

	/**
	 * 取得从Excel转换到Model的　List.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List getModelList(ImportVo vo) {
		String path = vo.getFilePath();
		if (ConfigConstant.isNull(path)) {
			path = ConfigConstant.getClassLoaderPath().replace("WEB-INF/classes/", "downloadFile/");
		}
		ConfigConstant.newCreateFolder(path);
		File execlFile = new File(path + vo.getFileName());
		if (isValidateExcelFormat(execlFile, vo.getModelName(), (Map<String, String>) vo.getParams("valueMap"), null)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("methodName", "getModelList");
			return (List) getEtm("execlToBean").execute(params);
		}
		return null;
	}

	/**
	 * 验证Xml文件配制的Excel标题在　Excel文件中是否在
	 */
	private boolean isValidateExcelFormat(File excelFile, String modelName, Map<String, String> valueMap,
			Map<String, String> args) {

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("methodName", "getModel");
		params.put("modelName", modelName);

		RuturnConfig config = (RuturnConfig) getEtm("implexecl").execute(params);

		params.put("methodName", "validateExcelFormat");
		params.put("excelFile", excelFile);
		params.put("modelName", config);
		params.put("valueMap", valueMap);

		return (Boolean) getEtm("execlToBean").execute(params);
	}

	/**
	 * 取得操纵Excel文件的实例
	 */
	public Execlplugins getEtm(String key) {
		if (null == plugins.get(key)) {
			if ("implexecl".equals(key)) {
				plugins.put("implexecl", new ImplExeclPluginsImpl());
			} else if ("execlToBean".equals(key)) {
				plugins.put("execlToBean", new ExeclToBeanPluginsImpl());
			}
		}
		return plugins.get(key);
	}

}
